package com.thon.service.paper;

import com.thon.commons.persistence.Page;
import com.thon.dao.paper.PaperDao;
import com.thon.dao.paper.RelationDao;
import com.thon.dao.system.AttachmentDao;
import com.thon.dao.system.UserDao;
import com.thon.entity.paper.Paper;
import com.thon.entity.paper.Relation;
import com.thon.entity.system.Attachment;
import com.thon.entity.system.User;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by Chen on 2016/2/22.
 */
@Service
@Transactional
public class PaperService {
    
    @Autowired
    private PaperDao paperDao;
    @Autowired
    private AttachmentDao attachmentDao;
    @Autowired
    private RelationDao relationDao;
    @Autowired
    private UserDao userDao;

    //get
    public Paper getPaper(int id){
        return paperDao.get(id);
    }

    //save
    public void savePaper(Paper paper){
        paperDao.save(paper);
    }

    //delete
    public void delPaper(Paper paper){
        paperDao.delete(paper);
    }

    //list
    public Page<Paper> findPapers(Page<Paper> page, Paper paper) {
        DetachedCriteria dc = paperDao.createDetachedCriteria();

        if (paper.getRelation() != null) {
            dc.add(Restrictions.eq("relation.id", paper.getRelation().getId()));
        }
        dc.addOrder(Order.desc("id"));

        return paperDao.find(page, dc);
    }

    //获得上传者
    public String getUploader(Integer attachmentId) {
        Attachment attachment = attachmentDao.get(attachmentId);
        Integer creatorId = attachment.getCreateBy();
        return userDao.get(creatorId).getName();
    }


    public void getCurPaper(Attachment attachment, Integer uid, String description) {

        Paper paper = new Paper();
        paper.setAttachment(attachment);
        Relation relation = relationDao.getRelationIdByStudentId(uid);
        paper.setRelation(relation);
        paper.setUploader(getUploader(attachment.getId()));
        paper.setDescription(description);
        User user = userDao.get(uid);
        user.setSchedule(5);
        userDao.save(user);
        paperDao.save(paper);
    }
}
